package org.example.zpqy.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Service
public class PlantWeatherAdvice {
    private static final Logger logger = LoggerFactory.getLogger(PlantDiseaseDetectionService.class);
    private static final String API_KEY = "05026462bec74d0bab71af99bfdf4ba9.6QtRhGK7snFoWIZ5";
    private static final String API_URL = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
    // 新增Jackson解析器
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public String getAiInfo(String WeatherInfo,String plantName) {
        try {

            HttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(API_URL);

            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", "Bearer " + API_KEY);

            String jsonBody = buildRequestBodyJson(WeatherInfo, plantName);
            StringEntity entity = new StringEntity(jsonBody, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpPost);
            String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            // 打印原始响应日志（关键调试信息）
            logger.info("智普API响应: {}", responseBody);

            return extractChineseContent(responseBody);
        } catch (IOException e) {
            logger.error("调用模型失败", e);
            return "调用模型失败: " + e.getMessage();
        }
    }

    // 修复1：补充Base64前缀，调整请求体格式
    private String buildRequestBodyJson(String WeatherInfo,String plantName) throws JsonProcessingException {
        // 优化提示词，明确任务
        String prompt = "请根据下面给出的天气信息及对应的植物给出防护建议，返回格式键为防治建议，分点回答并且标上序号";

        ObjectMapper mapper = new ObjectMapper();

        // 构造消息
        Map<String, Object> msg1 = new HashMap<>();
        msg1.put("role", "user");
        msg1.put("content", prompt + "天气信息是:"+WeatherInfo + "植物名称是:"+plantName);


        // 拼装请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "glm-4.5");
        requestBody.put("messages", Arrays.asList(msg1));
        requestBody.put("max_tokens", 4096);
        requestBody.put("temperature", 0.6);

        Map<String, String> thinking = new HashMap<>();
        thinking.put("type", "enabled");
        requestBody.put("thinking", thinking);

        return mapper.writeValueAsString(requestBody);
    }

    // 修复2：使用Jackson解析响应，支持复杂JSON结构
    private String extractChineseContent(String jsonResult) {
        try {
            JsonNode rootNode = objectMapper.readTree(jsonResult);

            // 提取正常响应内容
            JsonNode choicesNode = rootNode.get("choices");
            if (choicesNode != null && choicesNode.isArray() && choicesNode.size() > 0) {
                JsonNode messageNode = choicesNode.get(0).get("message");
                if (messageNode != null) {
                    JsonNode contentNode = messageNode.get("content");
                    if (contentNode != null && !contentNode.asText().isEmpty()) {
                        return contentNode.asText();
                    }
                }
            }

            // 提取错误信息（如API密钥无效、模型不支持等）
            JsonNode errorNode = rootNode.get("error");
            if (errorNode != null) {
                String errorMsg = errorNode.get("message").asText("未知错误");
                logger.error("模型返回错误: {}", errorMsg);
                return "分析失败: " + errorMsg;
            }

            // 未匹配到任何内容
            logger.warn("未从响应中提取到有效数据: {}", jsonResult);
            return "无法获取分析结果，请检查图片是否清晰或尝试重新上传";
        } catch (Exception e) {
            logger.error("解析响应失败", e);
            return "解析结果失败: " + e.getMessage();
        }
    }
}
